var user = require('../../utils/user.js');
import { request } from '../../services/_utils/util';
const api = require('../../services/config/api');
import Toast from '@vant/weapp/toast/toast';
var app = getApp();
Page({
  data: {
    loginData: {},
  },
  async wxLogin(e) {
    var that = this;
    wx.showModal({
      //手动授权弹窗
      title: '授权登录提示',
      content: '是否允许授权？',
      showCancel: true,
      confirmText: '允许',
      confirmColor: '#669F76',
      cancelColor: '#CC463D',
      success: async (res) => {
        if (res.confirm) {
          // 自定义加载图标
          Toast.loading({
            message: '加载中...',
            forbidClick: true,
            loadingType: 'spinner',
            duration: 0,
          });
          wx.login({
            success: (res) => {
              console.log(res);
              var obj = {};
              if (res.code) {
                wx.getUserInfo({
                  success: function (elm) {
                    console.log(123);
                    console.log(elm);
                    obj['code'] = res.code;
                    obj['userInfo'] = elm.userInfo;
                    obj['iv'] = elm.iv;
                    obj['encryptedData'] = elm.encryptedData;
                    that.doLogin(obj);
                  },
                });
              } else {
                console.log('获取用户登录态失败！' + res.errMsg);
              }
            },
          });
        } else if (res.cancel) {
          //用户取消
          wx.showToast({
            title: '取消授权',
            mask: true,
            icon: 'error',
          });
        }
      },
    });
  },
  doLogin: function (userInfo) {
    var that = this;
    request(api.AuthLoginByWeixin, userInfo, 'post').then(function (res) {
      console.log(res);
      Toast.clear();
      if (res.code == 0) {
        wx.showToast({
          title: res.msg,
          icon: 'error',
          duration: 2000,
        });
      } else {
        wx.showToast({
          title: '登录成功',
          icon: 'success',
          duration: 2000,
        });
        //存储用户信息
        wx.setStorageSync('token', res.data.token);
        wx.setStorageSync('userInfo', res.data.userInfo);
        //跳转到个人信息页
        wx.redirectTo({ url: '/pages/usercenter/index?currAuthStep=2' });
      }
    });
  },
  accountLogin() {
    wx.navigateTo({
      url: '/pages/login/account/index',
    });
  },
});
